package org.linlinjava.litemall.core.exception;

/**
 * @author: Destin
 * @date: 2021-12-31
 */
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public abstract class AbstractCoderException extends RuntimeException {
    private ErrorCode errorCode;
    private int errorType;
    private Map<String, Object> attributes;

    protected AbstractCoderException(ErrorCode code, int type) {
        this.errorType = type;
        this.init(code);
    }

    protected AbstractCoderException(ErrorCode code, String message, int type) {
        super(message);
        this.errorType = type;
        this.init(code);
    }

    protected AbstractCoderException(ErrorCode code, String message, Throwable ex, int type) {
        super(message, ex);
        this.errorType = type;
        this.init(code);
    }

    protected void init(ErrorCode code) {
        if (null == code) {
            throw new IllegalArgumentException("Error code is null.");
        } else {
            this.errorCode = code;
        }
    }

    public int getErrorType() {
        return this.errorType;
    }

    public ErrorCode getErrorCode() {
        return this.errorCode;
    }

    public AbstractCoderException putAttribute(String key, Object value) {
        if (null == this.attributes) {
            this.attributes = new HashMap();
        }

        this.attributes.put(key, value);
        return this;
    }

    public Map<String, Object> getAttributes() {
        return null == this.attributes ? Collections.emptyMap() : this.attributes;
    }

    public AbstractCoderException setAttributes(Map<String, Object> attributes) {
        if (null != attributes) {
            this.attributes = attributes;
        }

        return this;
    }

    public Throwable fillInStackTrace() {
        return this;
    }

    public String toString() {
        return this.getClass().getTypeName() + "{errorCode=" + this.errorCode + ", attributes=" + this.attributes + "}";
    }
}
